﻿using AutoMapper;
using B.S.BasicData.Api.Write.Application.Command.User;
using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Write.Application.Handler.User
{
    public class UpdateUserHandler : IRequestHandler<UpdateUserCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<UserModel> usersRepo;
        private readonly IMapper mapper;

        public UpdateUserHandler(IBaseRepository<UserModel> usersRepo, IMapper mapper)
        {
            this.usersRepo = usersRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(UpdateUserCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var user = usersRepo.GetAll().Where(x => x.UserName == request.UserName && x.Id != request.Id).FirstOrDefault();
            var users = usersRepo.GetAll().Where(x => x.UserName == request.UserName && x.Id != request.Id && x.IsDelete==false).Count();
            if (users == 1 )
            {
                res.Msg = "用户名已存在";
                res.Code = ApiEnum.Error;
                return Task.FromResult(res);
            }
            else
            {
                user = mapper.Map(request, user);
                user.UpdateName = "李四";
                user.UpdateTime = DateTime.Now;
                user.CreateName = "张三";
                user.CreateTime = DateTime.Now;
                int i = usersRepo.Update(user);
                if (i > 0)
                {
                    res.Msg = "修改成功";
                    res.Code = ApiEnum.Success;
                    res.Data = i;

                }
                else
                {
                    res.Msg = "修改失败";
                    res.Code = ApiEnum.Error;
                    res.Data = i;

                }
            }

            
            return Task.FromResult(res);
        }
    }
}
